package response

import (
	"google.golang.org/grpc/status"
	"net/http"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/rest/httpx"
)

type Body struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
}

// JwtUnauthorizedResult jwt认证失败返回给调用者
func JwtUnauthorizedResult(w http.ResponseWriter, r *http.Request, err error) {
	httpx.WriteJson(w, http.StatusUnauthorized, &Body{
		Code:    http.StatusUnauthorized,
		Data:    nil,
		Message: err.Error(),
	})
}
func Response(w http.ResponseWriter, resp interface{}, err error) {
	var body Body
	if err != nil {
		body.Code = -1
		body.Message = err.Error()
	} else {
		body.Message = "OK"
		body.Data = resp
	}
	httpx.OkJson(w, body)
}

func GrpcGatewayResponse(r *http.Request, w http.ResponseWriter, resp any, err error) {
	if err == nil {
		httpx.WriteJson(w, http.StatusOK, &Body{
			Message: "OK",
			Data:    resp,
		})
		return
	}

	causeErr := errors.Cause(err)
	// 先看是不是status,  FromError中会使用errors.As找整个错误链
	if s, ok := status.FromError(causeErr); ok {
		httpx.WriteJson(w, http.StatusOK, &Body{
			Code:    -1,
			Message: s.Message(),
		})
		return
	}

	// 兜底
	httpx.WriteJson(w, http.StatusOK, &Body{
		Code:    -1,
		Message: causeErr.Error(),
	})
}
